package com.kws.merchant.service.impl;


import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.write.style.column.SimpleColumnWidthStyleStrategy;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.kws.merchant.domain.Device;
import com.kws.merchant.domain.Item;
import com.kws.merchant.domain.OperationDevice;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.kws.merchant.domain.po.OperationDevicePo;
import com.kws.merchant.domain.vo.OperationDeviceVo;
import com.kws.merchant.mapper.OperationDeviceMapper;
import com.kws.merchant.service.DeviceService;
import com.kws.merchant.service.ItemService;
import com.kws.merchant.service.OperationDeviceService;
import com.kws.merchant.util.ExcelUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * 运维-设备台账(OperationDevice)表服务实现类
 *
 * @author yxy
 * @since 2024-10-25 09:17:53
 */
@Service("operationDeviceService")
public class OperationDeviceServiceImpl extends ServiceImpl<OperationDeviceMapper, OperationDevice> implements OperationDeviceService {

    @Resource
    private OperationDeviceMapper operationDeviceMapper;
    @Autowired
    private ItemService itemService;
    @Autowired
    private DeviceService deviceService;



    /**
     * 分页查询列表
     */
    @Override
    public Page<OperationDeviceVo> pageList(OperationDevicePo operationDevicePo) {
        Page<OperationDeviceVo> page = new Page<>(operationDevicePo.getPageSize(), operationDevicePo.getTotalPage());
        String deviceNO = operationDevicePo.getDeviceNO();//设备编号
        String itemId = operationDevicePo.getItemId();//项目id
        Integer totalPage = operationDevicePo.getTotalPage();
        Integer pageSize = (operationDevicePo.getPageSize()-1)*totalPage;
        String sql="";
        if (StringUtils.isNotEmpty(itemId)){
           sql+=" and it.id="+itemId;
        }
        if (StringUtils.isNotEmpty(deviceNO)){
            sql+=" and de.code= \'"+deviceNO+"\'";
        }
        List<OperationDeviceVo> operationDeviceVos = operationDeviceMapper.pageList(sql, pageSize, totalPage);
        Integer total = operationDeviceMapper.count(sql);
        page.setTotal(total);
        page.setRecords(operationDeviceVos);
        return page;
    }

    /**
     * 运维-设备台账导入 todo
     * @param file
     * @return
     */
    @Override
    public Object uploadExcel(MultipartFile file) {
            ArrayList<OperationDevice> operationDevices = new ArrayList<>();
        try {
            List<OperationDeviceVo> list = ExcelUtil.readExcel(ExcelUtil.convert(file).getAbsolutePath(), OperationDeviceVo.class);
            list.forEach(x->{
                OperationDevice operationDevice = new OperationDevice();
                String itemName = x.getItemName();
                String deviceId = x.getDeviceId();
                //根据设备名称获取设备信息
                Item item=itemService.getByName(itemName);
                if (ObjectUtils.isEmpty(item)){
                    throw new RuntimeException("没用找到该项目："+itemName);
                }
                //根据设备编码获取设备信息
               /* Device device = deviceService.getByCode(x.getCode());
                if (ObjectUtils.isEmpty(device)){
                    throw new RuntimeException("没用找到该设备编号："+x.getCode());
                }*/
                operationDevice.setItemId(item.getId());
//                operationDevice.setDeviceId(device.getId());
                operationDevice.setStatus(Integer.valueOf(x.getStatus()));
                operationDevice.setInstallationSite(x.getInstallationSite());
                operationDevice.setPrincipal(x.getPrincipal());
                operationDevice.setPrincipalPhone(x.getPrincipalPhone());
                operationDevices.add(operationDevice);
            });

        } catch (Exception e) {
            e.printStackTrace();
        }
        return  this.saveBatch(operationDevices);
    }

    /**
     * 运维-设备台账导出 todo
     * @return
     */
    @Override
    public Object exportExcel(HttpServletResponse response,OperationDevicePo operationDevicePo) {
        String fileName = ExcelUtil.getPath()+"-"+System.currentTimeMillis() + "";
        response.setCharacterEncoding("utf-8");
        // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
        try {
            fileName = URLEncoder.encode(fileName, "UTF-8").replaceAll("\\+", "%20");
            response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
            EasyExcel.write(response.getOutputStream(),OperationDeviceVo.class).registerWriteHandler(new SimpleColumnWidthStyleStrategy(15)).sheet("设备台账").doWrite(this.pageList(operationDevicePo).getRecords());
//            EasyExcel.write(response.getOutputStream(),OperationDeviceVo.class).registerWriteHandler(new SimpleColumnWidthStyleStrategy(15)).sheet("设备台账").doWrite((Collection<?>) null);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return fileName + ".xlsx";
    }

    /**
     * 运维-设备台账模板导出
     * @param response
     * @return
     */
    @Override
    public Object exportTemplate(HttpServletResponse response) {
        String fileName = ExcelUtil.getPath()+"-"+System.currentTimeMillis() + "";
        response.setCharacterEncoding("utf-8");
        // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
        try {
            fileName = URLEncoder.encode(fileName, "UTF-8").replaceAll("\\+", "%20");
            response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
            EasyExcel.write(response.getOutputStream(),OperationDeviceVo.class).registerWriteHandler(new SimpleColumnWidthStyleStrategy(15)).sheet("设备台账").doWrite((Collection<?>) null);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return fileName + ".xlsx";
    }


}
